package com.copm.demonstrationsystem.service.introductionfeatures.commons;

import com.copm.demonstrationsystem.commons.response.ResponseStatus;
import com.copm.demonstrationsystem.commons.util.ImageUtils;
import com.copm.demonstrationsystem.pojo.commons.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;

/**
 * @Author: Yuan Baiyu
 * @Date: Created in 16:47 2018/5/4
 */

@Service
public class SinglonImageHandle {

    private static Logger logger = LoggerFactory.getLogger(SinglonImageHandle.class);

    public ResponseStatus storeAndCheckImage(MultipartFile file) {
        ResponseStatus status = new ResponseStatus();
        String[] paths;
        try {
            //保存图片及返回图片的重命名
            //fileName = ImageUtils.store(ImageUtils.getImageDir(), file);

            paths = ImageUtils.storeAndCompressionImage(ImageUtils.getImageDir(),file);

            if(paths == null){
                throw new RuntimeException("图片存储失败了！");
            }

        } catch (FileNotFoundException e) {
            status.setStatue(0);
            status.setMessage("项目路径无法找到上传图片" + e.toString());
            logger.info("项目路径无法找到上传图片,图片上传失败！");
            return status;
        }
        //检验文件后缀
        if (ImageUtils.checkSuffix(paths[0]) == false) {
            status.setStatue(0);
            status.setMessage("文件格式出错，请确认后再次上传");
            logger.info("文件格式出错,上传失败！");
            return status;
        }
        status.setStatue(1);
        //通过返回的ResponseStatus的data属性传递fileName。
        status.setData(paths);
        return status;
    }


    public ResponseStatus deleteImage(Image image) {
        ResponseStatus status = new ResponseStatus();
        try {
            //从物理图片目录中删除图片
            ImageUtils.delete(ImageUtils.getImageDir(), image.getFileName());
        } catch (FileNotFoundException e) {
            status.setStatue(0);
            status.setMessage("项目路径无法找到待删除图片，错误信息：" + e.toString());
            logger.info("物理图片目录没有找到待删除图片，删除失败！");
            return status;
        }
        status.setStatue(1);
        return status;
    }
}
